package com.rslai.commons.http.tools;

import org.apache.http.*;
import org.apache.http.protocol.HttpContext;

import java.io.IOException;

/**
 * 调试处理器，会将http的 request 和 response 打印到控制台
 * Created by lrs on 2018/8/6.
 */
public class DebugInterceptor implements HttpRequestInterceptor, HttpResponseInterceptor {

    public static final DebugInterceptor instance = new DebugInterceptor();
    private static final String lineSeparator = System.getProperty("line.separator");

    /**
     * 默认构造方法
     */
    private DebugInterceptor() {

    }

    /**
     * 处理一个请求 request，会将请求信息打印到控制台
     * @param request 返回的 response
     * @param context 正在使用上下文
     * @throws HttpException HttpException
     * @throws IOException IOException
     */
    @Override
    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
        StringBuilder sb = new StringBuilder();
        sb.append(request.getRequestLine().toString()).append(lineSeparator);
        for (Header h : request.getAllHeaders()) {
            sb.append(">>> ").append(h).append(";").append(lineSeparator);
        }
        System.out.println(sb.toString());
    }

    /**
     * 处理一个响应 response，会将响应信息打印到控制台
     * @param response 返回的 response
     * @param context 正在使用上下文
     * @throws HttpException HttpException
     * @throws IOException IOException
     */
    @Override
    public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
        StringBuilder sb = new StringBuilder();
        sb.append(response.getStatusLine().toString()).append(lineSeparator);
        for (Header h : response.getAllHeaders()) {
            sb.append("<<< ").append(h).append(lineSeparator);
        }
        System.out.println(sb.toString());
    }

}
